<?php
namespace app\index\controller;

use \think\Controller;
//use think\facade\Request;
use think\Db;
use think\facade\Request;
use think\captcha\Captcha;
class Reg extends  Controller
{
    public function index()
    {
    	if(Request::isPost())
		{
			$post = input('post.');
			//验证验证码
			$validate = $post['code'];
			$re = $this->validatecheck($validate);
			if(!$re)
			{
				echo 12004;exit;
			}
			$salt = mt_rand(1000, 9999);
			$passwd = md5($post['passwd'].$salt);
			$user = ['user_name'=>$post['user_name'],'passwd'=>$passwd,'salt'=>$salt];
			$username = Db::table('shop_user')->where('user_name',$user['user_name'])->find();
			if($username>0)
			{
				echo 12002;exit;
			}
			$userphone = Db::table('shop_user_details')->where('phone',$post['phone'])->find();
			if($userphone>0)
			{
				echo 12003;exit;
			}
			// 启动事务
			Db::startTrans();
			try {
			    $user_id = Db::table('shop_user')->insertGetId($user);
				$userdetails = ['email'=>$post['email'],'phone'=>$post['phone'],'user_id'=>$user_id];
				$userdetails_id = Db::table('shop_user_details')->insertGetId($userdetails);
			    // 提交事务
			    Db::commit();
			} catch (\Exception $e) {
			    // 回滚事务
			    Db::rollback();
				echo 12000;exit;
			}
			if($userdetails_id>0)
			{
				echo 12001;
			}
			exit;
		}
    	return $this->fetch();
    }
	
	//验证码
	public function vali()
	{
		$config =    [
			'imageH'=>40,		    // 验证码字体大小
		    'fontSize'    =>    24,    
		    // 验证码位数
		    'length'      =>    3,   
		    // 关闭验证码杂点
		    'useNoise'    =>    false, 
		];
		$captcha = new Captcha($config);
		return $captcha->entry();
	}
	
	//验证码确认
	protected function validatecheck($validate)
	{
		$captcha = new Captcha();
		$re = $captcha->check($validate);
		return $re;		
	}
	
	//查询用户是否存在
	protected function checklive($post)
	{
			$manager_name = $post['manager_name'];
			$passwd= $post['passwd'] ;
			$re = Db::name('manager')
			->where('manager_name',$manager_name)
			->where('passwd',$passwd)
			->find();
			return $re;
	}
	
	//用于验证数据
	protected function logindatavali($post)
	{
		//验证验证码
		$validate = $post['validate'];
		$this->validatecheck($validate);
		//验证用户名和密码
		$usernameandpasswd = [
		    'username'  => $post['manager_name'],
		    'passwd' => $post['passwd']
		];
		$this->usernameandpasswd($usernameandpasswd);
	}
	
	//用户名密码校验
	protected function usernameandpasswd($usernameandpasswd)
	{
		$validate = new \app\admin\validate\Managervali;
		$result = $validate->check($usernameandpasswd);
		if(!$result){
			// 验证失败
			$this->error($validate->getError(),'admin/index/index');exit;
		   
		}		
	}

}
